import html2canvas from "html2canvas";
import jspdf from "jspdf";
import { getAllStyles, getTotalTemplate } from "./utils";

const toString = Object.prototype.toString;

const types = {
  object: "[object Object]",
  array: "[object Array]",
};

class PdfGenerator {
  /** pdf generator's options */
  _options;
  /** @type {HTMLDivElement} rootEl */
  rootEl;

  constructor(options) {
    if (toString.call(options) !== types.object) {
      throw new Error('options must be an object in class "PdfGenerator"');
    }

    const _options = options || {
      title: "PDFTemplate",
      template: "<div>hahaha</div>",
      scale: 3,
    };

    this._options = _options;
    this._initEl();
  }
  _initEl() {
    if (document.getElementById("rootEl")) {
      this.rootEl = document.getElementById("rootEl");
      return;
    }
    const rootEl = document.createElement("div");
    rootEl.id = "rootEl";
    document.documentElement.appendChild(rootEl);
    this.rootEl = rootEl;
  }
  /**
   * @param { HTMLElement } el
   */
  async download(el) {
    if (!el) {
      return;
    }

    this.rootEl.innerHTML = getTotalTemplate({
      template:
        el.innerHTML || this._options.template || `<h2>template is empty</h2>`,
      style: getAllStyles(),
    });

    const canvas = await this._getNewCanvas(this.rootEl);
    this._createPDF(canvas);
  }
  /**
   * 根据元素节点获取canvas
   * @param {HTMLElement} el
   */
  async _getNewCanvas(el) {
    const scale = this._options.scale || 1;
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");

    const elWidth = el.offsetWidth,
      elHeight = el.offsetHeight; // el.clientHeight > el.clientWidth ? el.clientWidth : el.clientHeight

    canvas.style.display = "none";

    canvas.width = elWidth * scale;
    canvas.height = elHeight * scale;

    canvas.style.height = elHeight + "px";
    canvas.style.width = elWidth + "px";

    context.scale(scale, scale);

    const opts = {
      scale,
      width: elWidth,
      height: elHeight,
      canvas,
      useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
    };

    return await html2canvas(el, {
      ...opts,
      backgroundColor: "#fff",
    });
  }
  /**
   * 根据canvas生成PDF
   * @param { HTMLCanvasElement } canvas
   */
  _createPDF(canvas) {
    const contentWidth = canvas.width,
      contentHeight = canvas.height;

    const pdf = new jspdf("l", "px", [contentWidth, contentHeight]);
    const img = canvas.toDataURL("img/png", 1);

    pdf.addImage(img, 0, 0, contentWidth, contentHeight);
    pdf.save(`${this._options.title || "example"}.pdf`);
  }
}

export default PdfGenerator;
